package handler.commandprocessor;

import dao.GroupDAO;
import dao.RelationDAO;
import handler.CommandHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import message.Command;
import message.command.JoinGroupCommand;
import message.receive.JoinGroupReceive;
import route.Router;
import util.Constants;

public class JoinGroupProcessor implements CommandHandler.CommandProcessor
{
    private GroupDAO    groupDAO;
    private RelationDAO relationDAO;
    private Router      router;

    public JoinGroupProcessor(GroupDAO groupDAO, RelationDAO relationDAO, Router router)
    {
        this.groupDAO = groupDAO;
        this.relationDAO = relationDAO;
        this.router = router;
    }

    @Override
    public void process(Command command, ChannelHandlerContext ctx)
    {
        String           groupName = ((JoinGroupCommand) command).getGroupName();
        String           groupId   = groupDAO.find(groupName);
        JoinGroupReceive receive   = new JoinGroupReceive();
        if (groupId == null)
        {
            receive.setCode((byte) 100);
            receive.setCodeMsg("群聊不存在");
        }
        Attribute<String> attr     = ctx.channel().attr(Constants.CLIENT_ID);
        String            clientId = attr.get();
        try
        {
            relationDAO.save(groupId, clientId);
            router.addToGroup(groupId, clientId,ctx.channel());
            receive.setCode((byte) 0);
            receive.setCodeMsg("加入群聊成功");
        }
        catch (Exception e)
        {
            receive.setCode((byte) 1);
            receive.setCodeMsg(e.getMessage());
        }
        ctx.channel().writeAndFlush(receive);
    }
}
